"""错误处理模块

提供统一的错误处理功能，包括自定义异常类和错误处理函数。
"""

from fastapi import Request, status
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from utils.logger import get_logger

# 初始化日志记录器
logger = get_logger('error_handler')

# 自定义异常类
class AppError(Exception):
    """应用程序自定义异常基类"""
    def __init__(self, message: str, status_code: int = 500):
        self.message = message
        self.status_code = status_code
        super().__init__(self.message)

class FileProcessingError(AppError):
    """文件处理错误"""
    def __init__(self, message: str, status_code: int = 400):
        super().__init__(message, status_code)

class KnowledgeGraphError(AppError):
    """知识图谱处理错误"""
    def __init__(self, message: str, status_code: int = 500):
        super().__init__(message, status_code)

class LLMError(AppError):
    """LLM处理错误"""
    def __init__(self, message: str, status_code: int = 503):
        super().__init__(message, status_code)

# 错误处理函数
async def app_exception_handler(request: Request, exc: AppError):
    """处理应用程序自定义异常"""
    logger.error(f"应用程序错误: {exc.message}")
    return JSONResponse(
        status_code=exc.status_code,
        content={"error": exc.message}
    )

async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """处理请求验证错误"""
    logger.error(f"请求验证错误: {str(exc)}")
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content={"error": f"请求参数验证失败: {str(exc)}"}
    )

async def general_exception_handler(request: Request, exc: Exception):
    """处理通用异常"""
    logger.error(f"未处理的异常: {str(exc)}")
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={"error": f"服务器内部错误: {str(exc)}"}
    )

# 注册错误处理器
def register_exception_handlers(app):
    """注册所有异常处理器"""
    app.add_exception_handler(AppError, app_exception_handler)
    app.add_exception_handler(RequestValidationError, validation_exception_handler)
    app.add_exception_handler(Exception, general_exception_handler)